<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/28
 * Time: 18:13
 */

class WxPosition {
    static $_distance = null;
    public static function create(){
        if(null== self::$_distance){
            self::$_distance = new self;
        }
        return self::$_distance;
    }
    private $token_dir ="";
    public function __construct(){
        $this->token_dir =DXW_CACHE_CONF."/jsapi_ticket.json";
    }

    public function getSignPackage() {
        $appId = DXW_WX_APPID;
        $appSecret = DXW_WX_APP_SEC;
        $jsapiTicket = $this->getJsApiTicket($appId,$appSecret);
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "{$protocol}{$_SERVER["HTTP_HOST"]}{$_SERVER["REQUEST_URI"]}";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        $string = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";

        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }
    public  function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    public function getJsApiTicket($appId,$appSecret) {
        $data = @json_decode(file_get_contents($this->token_dir),true);
        if (isset($data["expire_time"])) {
            if($data["expire_time"]< time()){
                $accessToken = $this->getAccessToken($appId,$appSecret);
                $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={$accessToken}";
                $res = json_decode($this->httpGet($url),true);
                $ticket = $res["ticket"];
                if ($ticket) {
                    $data["expire_time"] = time() + 7000;
                    $data["jsapi_ticket"] = $ticket;
                    //$fp = fopen($_SERVER['DOCUMENT_ROOT']."/jsapi_ticket.json", "w");
                    $fp = fopen($this->token_dir, "w");
                    fwrite($fp, json_encode($data));
                    fclose($fp);
                }
            }else{
                $ticket = $data["jsapi_ticket"];
            }

        } else {
            $accessToken = $this->getAccessToken($appId,$appSecret);
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={$accessToken}";
            $res = json_decode($this->httpGet($url),true);
            $ticket = $res["ticket"];
            if ($ticket) {
                $data["expire_time"] = time() + 7000;
                $data["jsapi_ticket"] = $ticket;
//                $fp = fopen($_SERVER['DOCUMENT_ROOT']."/jsapi_ticket.json", "w");
                $fp = fopen($this->token_dir, "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        }
        return $ticket;
    }

    public function getAccessToken($appId,$appSecret) {
        $data = @json_decode(file_get_contents($this->token_dir),true);
        if (isset($data["expire_time"])) {
            if($data["expire_time"] < time()){
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
                $res = json_decode($this->httpGet($url),true);
                $access_token = $res["access_token"];
                if ($access_token) {
                    $data["expire_time"] = time() + 7000;
                    $data["access_token"] = $access_token;
//                    $fp = fopen($_SERVER['DOCUMENT_ROOT']."/jsapi_ticket.json", "w");
                    $fp = fopen($this->token_dir, "w");
                    fwrite($fp, json_encode($data));
                    fclose($fp);
                }
            }else{
                $access_token = $data["access_token"];
            }
        } else {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
            $res = json_decode($this->httpGet($url),true);
            $access_token = $res["access_token"];
            if ($access_token) {
                $data["expire_time"] = time() + 7000;
                $data["access_token"] = $access_token;
//                $fp = fopen($_SERVER['DOCUMENT_ROOT']."/jsapi_ticket.json", "w");
                $fp = fopen($this->token_dir, "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        }
        return $access_token;
    }

    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

}